/**
 * Copyright 2025 Beijing Volcano Engine Technology Co., Ltd. All Rights Reserved.
 * SPDX-license-identifier: BSD-3-Clause
 */

import { requestGetMethod, requestPostMethod, resultHandler } from './base';
import { ACTIONS, RequestParams, RequestResponse } from './type';

// 定义API配置接口
interface ApiConfigItem {
  action: ACTIONS;
  apiBasicParams: string;
  method?: 'get' | 'post';
  useAuth?: boolean;
  isSimpleApi?: boolean;
}

const APIS_CONFIG: readonly ApiConfigItem[] = [
  {
    action: ACTIONS.StartVoiceChat,
    apiBasicParams: `?Name=start&Action=${ACTIONS.StartVoiceChat}&Version=2024-12-01`,
    method: 'post',
    useAuth: true,
  },
  {
    action: ACTIONS.UpdateVoiceChat,
    apiBasicParams: `?Name=update&Action=${ACTIONS.UpdateVoiceChat}&Version=2024-12-01`,
    method: 'post',
    useAuth: true,
  },
  {
    action: ACTIONS.StopVoiceChat,
    apiBasicParams: `?Name=stop&Action=${ACTIONS.StopVoiceChat}&Version=2024-12-01`,
    method: 'post',
    useAuth: true,
  },
  {
    action: ACTIONS.StartVoiceChatSimple,
    apiBasicParams: `?Action=StartVoiceChat`,
    method: 'post',
    useAuth: true,
    isSimpleApi: true,
  },
  {
    action: ACTIONS.StopVoiceChatSimple,
    apiBasicParams: `?Action=StopVoiceChat`,
    method: 'post',
    useAuth: true,
    isSimpleApi: true,
  },
];

type ApiNames = (typeof APIS_CONFIG)[number]['action'];
type RequestFn = <T extends keyof RequestResponse>(params?: RequestParams[T]) => RequestResponse[T];
type PromiseRequestFn = <T extends keyof RequestResponse>(
  params?: RequestParams[T]
) => Promise<RequestResponse[T]>;
type Apis = Record<ApiNames, RequestFn | PromiseRequestFn>;

const APIS = APIS_CONFIG.reduce((store, cur) => {
  const { action, apiBasicParams, method = 'get', useAuth = false, isSimpleApi = false } = cur;
  store[action] = async (params: any) => {
    // 处理简化API的情况
    if (isSimpleApi) {
      // 如果是字符串，直接将roomId作为URL参数拼接
      if (typeof params === 'string') {
        const urlWithRoomId = `${apiBasicParams}&roomId=${params}`;
        const queryData = await requestPostMethod(urlWithRoomId, true, {}, useAuth)({});
        const res = await queryData?.json();
        return resultHandler(res);
      }
      // 如果是对象且包含roomId，也作为URL参数拼接
      if (params && params.roomId) {
        const urlWithRoomId = `${apiBasicParams}&roomId=${params.roomId}`;
        const queryData = await requestPostMethod(urlWithRoomId, true, {}, useAuth)({});
        const res = await queryData?.json();
        return resultHandler(res);
      }
    }
    
    // 处理普通API的情况
    const requestParams = params || {};
    const queryData =
      method === 'get'
        ? await requestGetMethod(apiBasicParams, {}, useAuth)(requestParams)
        : await requestPostMethod(apiBasicParams, true, {}, useAuth)(requestParams);
    
    const res = await queryData?.json();
    return resultHandler(res);
  };
  return store;
}, {} as Apis);

export default APIS;
